package com.javalab._6feature._7io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class _4ByteIO {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 准备好文件
        File folder = new File("D:/myfolder");
        folder.mkdir();
        File file = new File("D:/myfolder/2.txt");
        file.createNewFile();

        // 创建对象
        MyObject object = new MyObject();
        object.setName("小明");
        object.setAge(22);
        object.setSex(true);
        object.setWeight(Double.valueOf("65"));
        object.setSalary(Float.valueOf("20000"));
        System.out.println("序列化前:" + object.toString());

        // 将对象序列化到文件
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream outputStream = new ObjectOutputStream(fos);
        outputStream.writeObject(object);
        // 切记要关闭资源，关闭顺序与打开顺序相反
        outputStream.close();
        fos.close();

        // 反序列化成对象
        FileInputStream fis = new FileInputStream(file);
        ObjectInputStream inputStream = new ObjectInputStream(fis);
        MyObject o = (MyObject) inputStream.readObject();
        // 切记要关闭资源，关闭顺序与打开顺序相反
        inputStream.close();
        fis.close();

        System.out.println("序列化后:" + o.toString());
    }
}
